﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using System.IO;
using System.Linq;
using System.Text;
namespace Localize
{
    /// <summary>
    /// i18n是“国际化”的简称,通常与i18n相关的还有L10n（“本地化”的简称）
    /// </summary>
    public class ExtractI18N
    {
        static public readonly string csFolder = "";
        static public readonly string luaFolder = "";

        static public void Extract(string fileData,string fileName,List<string> container,List<string>keys)
        {
            //i18n._("frind_list","好友列表  {0}/{1}")
            //MatchCollection matches = Regex.Matches(file, "i18n\\._\\(\\\"(.+?)\\\"", RegexOptions.IgnorePatternWhitespace);
            MatchCollection matches = Regex.Matches(fileData, "i18n\\._\\((\\\"(.+?)\\\")\\)", RegexOptions.IgnorePatternWhitespace);
            foreach (Match match in matches)
            {
                string key = match.Groups[1].Value;
                string value = null;
                MatchCollection values = Regex.Matches(key, "(\\\"(.+?)\\\")", RegexOptions.IgnorePatternWhitespace);

                bool isDuplicate = false;
                if (values.Count < 1)
                    continue;
                key = values[0].Value;
                if (keys.Contains(key))
                    isDuplicate = true;
                else 
                    keys.Add(key);
                if(values.Count > 1)
                    value = values[1].Value;
                if (isDuplicate)
                {
                    if(value != null)
                        container.Add(key + ":"+ value + "  ==> " + fileName);
                }
                else
                    container.Add(key + ":"+ (value==null? "\"null\"":value));
            }
        }

        [MenuItem("Tools/i18n/Extract", false, 17)]
        static private void Test()
        {
            Debug.Log("开始提取多语言================="); 
            string localPath = "";

            List<string> txt = new List<string>();
            List<string> allKeys = new List<string>(); 
            //script
            int len = Application.dataPath.Length;
            foreach (string file in Directory.GetFiles(Application.dataPath + "/" + csFolder, "*.cs", SearchOption.AllDirectories))
            {
                localPath = "Assets" + file.Substring(len);
                FileInfo f = new FileInfo(file);
                ExtractI18N.Extract((AssetDatabase.LoadAssetAtPath(localPath, typeof(TextAsset)) as TextAsset).text
                    ,f.Name,txt,allKeys);
            }
            //lua
            foreach (string file in Directory.GetFiles(Application.dataPath + "/" + luaFolder, "*.lua", SearchOption.AllDirectories))
            {
                localPath = "Assets" + file.Substring(len);
                FileInfo f = new FileInfo(file);
                ExtractI18N.Extract(File.ReadAllText(file)
                    ,f.Name,txt,allKeys);
            }
            //save
            TextAsset t = Resources.Load<TextAsset>("Localized");
            string outPath = AssetDatabase.GetAssetPath(t);
            //Application.dataPath + "/i18n/sentence.txt";
            FileInfo fi = new FileInfo(outPath);
            fi = new FileInfo(fi.Directory.Parent.FullName+"/sentence.txt");
            if(!fi.Directory.Exists)
                Directory.CreateDirectory(fi.Directory.FullName);
            using (FileStream fs =File.Open(fi.FullName,FileMode.OpenOrCreate))
            {
            }
            txt.Insert(0,"{");
            txt.Add("}");
            File.WriteAllLines(fi.FullName, txt.ToArray(), Encoding.UTF8);
            Debug.Log("多语言提取完毕=================");
            AssetDatabase.Refresh();
        }
    }
}